/**
 * wrap opentype.js
 */

import Promise from 'bluebird';

const opentype = {
    setup() {
        return new Promise(resolve => {
            require.ensure(['opentype.js'], () => {
                resolve(require('opentype.js'));
            });
        })
        .timeout(5000, 'OpenType.js load error')
        .then(opentype => {
            this._opentype = opentype;

            Object.assign(this, opentype, {
                load: Promise.promisify(opentype.load),
                loadFromFile(file) {
                    return new Promise((resolve, reject) => {
                        const reader = new FileReader();

                        reader.onload = () => {
                            resolve(reader.result);
                        };

                        reader.onerr = () => {
                            reject(new Error('File read error'));
                        };

                        reader.readAsArrayBuffer(file);
                    })
                    .then(buf => {
                        return this.parse(buf);
                    });
                }
            });

            return this;
        });
    }
};

export default opentype;
